from django.shortcuts import render,redirect,HttpResponse,reverse
from rbac import  models
"""角色管理"""

def role_list(request):
    """
    角色列表
    :param request:
    :return:
    """
    role_queryset = models.Role.objects.all()
    return render(request,'rbac/role_list.html',{'roles':role_queryset})


def role_add(request):
    """
    添加角色
    :param request:
    :return:
    """
    if request.method == 'POST':
        role_name = request.POST.get('name','')
        if role_name:
            models.Role.objects.create(title=role_name)
            return redirect(reverse('rbac:role_list'))
    return  render(request,'rbac/role_add.html')


def role_edit(request,role_id):
    """
    编辑角色
    :param request:
    :param role_id:
    :return:
    """
    role_obj = models.Role.objects.filter(pk=role_id).first()
    role_queryset = models.Role.objects.all().values('title')
    role_list = [ item['title']for item in role_queryset]
    print(role_list)
    status={}
    if request.method == 'POST':
        new_role = request.POST.get('name')
        if new_role == role_obj.title:
            status['msg']='角色名未做任何修改'
        elif new_role in role_list:
            status['msg'] = '该角色已经存在，请重做修改'
        else:
            models.Role.objects.update_or_create(title=new_role)
            return redirect(reverse('rbac:role_list'))
    return  render(request,'rbac/role_edit.html',locals())


def role_del(request,role_id):
    """
    删除角色
    :param request:
    :param role_id:
    :return:
    """
    cancel_url = '/rbac/role/list/'
    if request.method == 'POST':
        models.Role.objects.filter(pk=role_id).delete()
        return redirect(reverse(('rbac:role_list')))
    return  render(request, 'rbac/del.html', {'cancel':cancel_url})